package com.gcph.zhuoba.main.activitys;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.gcph.zhuoba.R;
import com.gcph.zhuoba.main.bean.ResourceData;
import com.gcph.zhuoba.main.bean.SocketData;
import com.gcph.zhuoba.main.common.BaseActivity;
import com.gcph.zhuoba.main.common.Constant;
import com.gcph.zhuoba.main.view.BallJiasaiView;
import com.gcph.zhuoba.util.L;
import com.gcph.zhuoba.util.SocketClient;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

/**
 * 录像activity
 * 
 * @author Administrator
 */
public class VedioActivity extends BaseActivity {
	@SuppressLint("SimpleDateFormat")
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");

	// 退出
	private Button btn_teaching_quit;
	// 采集球型
	private Button btn_teaching_revideo;
	private Button btn_teaching_video_upload;
	private Button btn_teaching_generate;
	
	private ProgressBar pro_progressbar_upload;

	private VideoView video_view;
	private SocketClient socketClient;

	// 难度星级
	private RatingBar teach_rating_bar;

	private SeekBar ball_power_bar;

	private String fileno;
	private String resourceNo;
	private int imgFileId;
	private int videoFileId;
	private String videoFileUrl;
	//线路数据
	private String resourceLine;
	// 球型位置json数据
	private String ballsPositionData;
	//教案小类型 
	private Integer resourceSmallType;

	// 单例对象 handle
	private static Handler handler;
	
	//自定义toast
	private Toast toast;
	private View toastView;
	private TextView toastMsg;
	
	// 接收进度
	public static void acceptRate(Message rate) {
		handler.sendMessage(rate);
	}

	// 得到单例对象
	private void initHandlerInstance() {
			handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {

					if (SocketClient.VEDIO_UPLOAD_RATE.equals(msg.what) && null != msg.obj) {
						int rate = 0;
						try {
							rate = Integer.parseInt((String) msg.obj);
						} catch (Exception e) {
							// rate = 0;
						}
						L.d("rate==" + rate);
						pro_progressbar_upload.setProgress(rate);
					}

					// 视频上传成功
					if (SocketClient.VEDIO_UPLOAD_SUCCESS.equals(msg.what)) {
						L.d("上传成功");
						pro_progressbar_upload.setProgress(50);
						SocketData socketData = (SocketData) msg.obj;
						if (null != socketData) {
							//得到线路数据
							resourceLine = socketData.getLine();
							videoFileId = socketData.getFileid();
							videoFileUrl = socketData.getUrl();
							
							String fileName = getFileNameFromUrl(videoFileUrl);
							L.d("==上传成功的videoFileUrl=="+videoFileUrl);
							downLoadVedio(videoFileUrl,fileName);
						}
					}
				}
			};
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		fullScreen(true);
		//屏蔽home键
		this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);
		setContentView(R.layout.activity_teaching_vedio);
		
		toastView = getLayoutInflater().inflate(R.layout.layout_toast, null);
		toastMsg = (TextView)toastView.findViewById(R.id.toast_msg);
		showToast("请按桌面提示进行操作");
		
		viewInit();
		setBtnClickListener();

		socketClient = SocketClient.getInstance();

		fileno = this.getIntent().getStringExtra("fileno");
		resourceNo = this.getIntent().getStringExtra("no");
		imgFileId = this.getIntent().getIntExtra("imgFileId", 0);
		ballsPositionData = this.getIntent().getStringExtra("ballsPositionData");
		resourceSmallType = this.getIntent().getIntExtra("resourceSmallType", 0);
		initHandlerInstance();
	}

	/**
	 * 按钮初始化
	 */
	private void viewInit() {
		btn_teaching_revideo = (Button) this.findViewById(R.id.btn_teaching_revideo);
		btn_teaching_video_upload = (Button) this.findViewById(R.id.btn_teaching_video_upload);
		btn_teaching_generate = (Button) this.findViewById(R.id.btn_teaching_generate);
		btn_teaching_quit = (Button) this.findViewById(R.id.btn_teaching_quit);
		
		
		
		video_view = (VideoView) this.findViewById(R.id.video_view);
		video_view.setBackgroundDrawable(getResources().getDrawable(R.drawable.video_preview));
		
		pro_progressbar_upload = (ProgressBar) this.findViewById(R.id.pro_progressbar_upload);
		teach_rating_bar = (RatingBar) this.findViewById(R.id.teach_rating_bar);
		ball_power_bar = (SeekBar) this.findViewById(R.id.ball_power_bar);
	}

	/**
	 * 设置按钮动作
	 */
	private void setBtnClickListener() {
		btn_teaching_quit.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				socketClient.exit();
				finish();
			}
		});

		// 重新录像
		btn_teaching_revideo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				//重新录像时重置 录像的名称
				resourceNo = "resource_"+sdf.format(new Date());
				socketClient.send(
						"{\"method\":\"" + Constant.SOCKET_METHOD_RE_VEDIO + "\",\"videono\":\"" + resourceNo + "\"}");
			}
		});
		// 上传录像
		btn_teaching_video_upload.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				socketClient.send(
						"{\"method\":\"" + Constant.SOCKET_METHOD_UPLOAD_VEDIO + "\",\"videono\":\"" + resourceNo + "\"}");
			}
		});
		// 生成教案
		btn_teaching_generate.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				// 难度
				float star = teach_rating_bar.getRating();
				// 力度
				int ballPower = ball_power_bar.getProgress();
				// 加赛
				ResourceData rData = new ResourceData();
				rData.setJiasaiX(BallJiasaiView.jiasaiX);
				rData.setJiasaiY(BallJiasaiView.jiasaiY);
				rData.setBallPower(ballPower);
				rData.setBallsPositionData(ballsPositionData);
				String resourceData = new Gson().toJson(rData);

				L.d("star==" + star);
				L.d("ballPower==" + ballPower);

				int intStar = (int) star;
				Intent intent = new Intent(VedioActivity.this, ResourceInputActivity.class);
				intent.putExtra("resourceType", Constant.RESOURCE_TYPE_JIAOAN);
				
				intent.putExtra("resourceLine", resourceLine);
				intent.putExtra("star", intStar);
				intent.putExtra("no", resourceNo);
				intent.putExtra("resourceData", resourceData);
				intent.putExtra("imgFileId", imgFileId);
				intent.putExtra("videoFileId", videoFileId);
				intent.putExtra("resourceSmallType", resourceSmallType);
				if(null  != toast)
				{
					toast.cancel();
				}
				startActivityForResult(intent, 0);
			}
		});
		
	}
	
	/*
	 * 下载视频，并保存到存储卡
	 */
	private void downLoadVedio(String remoteFile,String targetFile)
	{
		HttpUtils http = new HttpUtils();
		String url = getResources().getString(R.string.server_root_url) +remoteFile;
		final String  target = Environment.getExternalStorageDirectory().getPath()+"/DCIM/Camera/"+targetFile;
		File file =new File(target);
		if(file.exists())
		{
			file.delete();
		}
        http.download(url, target, true, true,  
                new RequestCallBack<File>() {  
                    @Override  
                    public void onStart() {  
                    	L.d("=====开始下载=====");
                    }  

                    @Override  
                    public void onLoading(long total, long current, boolean isUploading) {  
                        super.onLoading(total, current, isUploading);  
                        
                        int rate = (int) ((double) current/ (double) total * 50);
                        rate+=50;
                        L.d("=====下载进度====="+rate);
                        Message msg_dowload= new Message();
                        msg_dowload.what=SocketClient.VEDIO_UPLOAD_RATE;
                        msg_dowload.obj=rate+"";
    					handler.sendMessage(msg_dowload);
                    }  

                    @Override  
                    public void onSuccess(ResponseInfo<File> responseInfo) { 
                    	
                    	L.d("=====下载成功=====");
                    	video_view.setBackgroundDrawable(null);
						video_view.setVideoURI(Uri.parse(target));
						
						MediaController mediaco = new MediaController(VedioActivity.this);
						video_view.setMediaController(mediaco);
						mediaco.setMediaPlayer(video_view);
						video_view.seekTo(1);
                    }  

                    @Override  
                    public void onFailure(HttpException error, String msg) {  
                    	
                    	 L.d("下载失败====");
                    }

                });  
	}
	
	/**
	 * 
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == 0){
			if(null != socketClient)
			{
				socketClient.exit();
			}
			finish();
        } 
		
		if(resultCode == 1){
			
        }
    }
	
	
	/**
	 * 显示Toast,防止延迟
	 * @param msg
	 */
	private void showToast(String msg){
		
		if(null == toastView)
		{
			toastView = getLayoutInflater().inflate(R.layout.layout_toast, null);
		}
		if(null== toastMsg)
		{
			toastMsg = (TextView)toastView.findViewById(R.id.toast_msg);
		}
		if (toast != null)
	    {
			toast.setView(toastView);
			toastMsg.setText(msg);
	        toast.setDuration(Toast.LENGTH_LONG);
	        toast.show();
	    } else
	    {
			toast=new Toast(getApplicationContext());
			
			toast.setView(toastView);
			toastMsg.setText(msg);
			toast.setDuration(Toast.LENGTH_LONG);
			toast.show();
	    }
	}
	
	//===========================禁用home键，返回键和菜单键====================================
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return false;
		} else if (keyCode == KeyEvent.KEYCODE_MENU) {
			return false;
		} else if (keyCode == KeyEvent.KEYCODE_HOME) {
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
}